package com.dy.分类.搜索.岛屿数量;

import java.util.LinkedList;
import java.util.Queue;

/*
给定一个由 '1'（陆地）和 '0'（水）组成的的二维网格，计算岛屿的数量。
一个岛被水包围，并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。你可以假设网格的四个边均被水包围。

示例 1:

输入:
11110
11010
11000
00000

输出: 1
示例 2:

输入:
11000
11000
00100
00011

输出: 3
 */
public class Solution {
    public int numIslands(char[][] grid) {
        if (grid.length == 0) return 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (visited[i][j] == false && grid[i][j] == '1') {
                    DFS(grid, visited, i, j);
                    res += 1;
                }

            }
        }
        return res;
    }

    private void DFS(char[][] grid, boolean[][] visited, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || visited[i][j] == true || grid[i][j] == '0') {
            return;
        }
        visited[i][j] = true;
        DFS(grid, visited, i + 1, j);
        DFS(grid, visited, i - 1, j);
        DFS(grid, visited, i, j + 1);
        DFS(grid, visited, i, j - 1);
    }

    public int numIslands2(char[][] grid) {
        if (grid.length == 0) return 0;
        boolean[][] visited = new boolean[grid.length][grid[0].length];
        Queue<int[]> queue = new LinkedList();
        int res = 0;
        for (int i = 0; i < grid.length; i++) {
            for (int j = 0; j < grid[0].length; j++) {
                if (visited[i][j] == false && grid[i][j] == '1') {
                    queue.add(new int[]{i, j});
                    BFS(queue, grid, visited);
                    res++;
                }
            }
        }
        return res;
    }

    private void BFS(Queue<int[]> queue, char[][] grid, boolean[][] visited) {
        while (!queue.isEmpty()) {
            int i = queue.peek()[0];
            int j = queue.peek()[1];
            queue.poll();
            visited[i][j] = true;
            add(queue, grid, visited, i + 1, j);
            add(queue, grid, visited, i - 1, j);
            add(queue, grid, visited, i, j + 1);
            add(queue, grid, visited, i, j - 1);
        }
    }

    private void add(Queue<int[]> queue, char[][] grid, boolean[][] visited, int i, int j) {
        if (i < 0 || i >= grid.length || j < 0 || j >= grid[0].length || visited[i][j] == true ) {
            return;
        }
        visited[i][j] = true;
        if(grid[i][j] == '0') return;
        queue.add(new int[]{i, j});
    }


}
